
import os
import shutil
import socket
import ssl
import logging
import time


def check_string(s):
    # 字符串不为空不粉None
    if s is not None and len(s.strip()) > 0:
        return True
    else:
        return False


def getCdnDomains(ssl, domain=[]):
    # 取得符合条件的域名
    domains = []
    for d in domain:
        for s in ssl:
            d_main = getMainDomain(d)
            s_main = getMainDomain(s)
            d_child = getChildDomain(d)
            s_child = getChildDomain(s)
            if d_main == s_main:
                if d_child.count('.') == s_child.count('.'):
                    dc_arr = d_child.split('.')
                    sc_arr = s_child.split('.')
                    if sc_arr[0] == "*":
                        sc_arr[0] = dc_arr[0]
                    if '.'.join(str(i) for i in dc_arr) == '.'.join(str(i) for i in sc_arr):
                        domains.append(d)
    return domains


def isMap(obj):
    # 判断是否是map
    return isinstance(obj, dict)


def dict_key_exists(dictData, key):
    if isinstance(dictData, dict) and key in dictData.keys():
        return True
    else:
        return False


def getTimestamp(val=None) -> int:
    # 取当前本地的timestamp 传入值则转换没有传入则用当前时间
    if val == None:
        val = time.localtime()
    else:
        val = time.strptime(val, "%Y-%m-%d %H:%M:%S")

    return int(time.mktime(val))


def getDateTime(val=None):
    # 取本地时间返回标准字符串，传入则转换
    if val == None:
        val = time.localtime()
    else:
        val = val
    return time.strftime("%Y-%m-%d %H:%M:%S", val)


def getChildDomain(txt) -> str:
    # 从多级域名中取子域名字符串
    arr = txt.split('.')
    main = '.'.join(str(i) for i in arr[-2:])
    return remove_trailing_char(txt.replace(main, ""), ".")


def getMainDomain(txt) -> str:
    # 从多级域名中取主域名
    arr = txt.split('.')
    return '.'.join(str(i) for i in arr[-2:])


def remove_trailing_char(string, char):
    # 去除末尾的特定字符
    if string.endswith(char):
        return string[:-1]
    else:
        return string


def unzip_file(zip_path, extract_path):
    print(f'解压文件...')
    os.system(f'unzip -o {zip_path} -d {extract_path}')


def zip_files(path, filename):
    print('压缩文件...', path, filename)
    if os.path.exists(path):
        shutil.make_archive(f"{path}/{filename}", 'zip', path)


def get_ssl_certificate_info(domain):
    try:
        # 建立一个与目标域名的SSL连接，并设置连接超时时间为5秒
        context = ssl.create_default_context()
        with socket.create_connection((domain, 443), timeout=5) as sock:
            with context.wrap_socket(sock, server_hostname=domain) as ssock:
                # 获取SSL证书
                cert = ssock.getpeercert()

        # 打印证书信息
        print(cert)
        print("Subject:", cert['subject'])
        print("Issuer:", cert['issuer'])
        print("Valid From:", cert['notBefore'])
        print("Valid Until:", cert['notAfter'])
    except (socket.gaierror, ConnectionRefusedError, ssl.CertificateError, socket.timeout) as e:
        print(f"Error connecting to {domain}: {e}")
        return {"code": 0, "message": "not ssl"}
